#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
启动儿童故事绘本创作平台后端服务
"""
import os
import sys
import subprocess
import time

# 确保当前目录是项目根目录
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)

# 检查Python版本
if sys.version_info < (3, 8):
    print("错误: 本项目需要Python 3.8或更高版本。")
    sys.exit(1)

def check_dependencies():
    """检查项目依赖是否已安装"""
    try:
        import fastapi
        import uvicorn
        print(f"已安装 FastAPI {fastapi.__version__}")
        print(f"已安装 Uvicorn {uvicorn.__version__}")
        return True
    except ImportError:
        return False

def install_dependencies():
    """安装项目依赖"""
    print("正在安装项目依赖...")
    try:
        subprocess.run(
            [sys.executable, "-m", "pip", "install", "-r", "requirements.txt"],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        print("依赖安装成功！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"依赖安装失败: {e.stderr}")
        print("\n请尝试手动安装依赖：")
        print(f"{sys.executable} -m pip install -r requirements.txt")
        return False

def start_server():
    """启动FastAPI服务"""
    print("\n正在启动儿童故事绘本创作平台后端服务...")
    print("服务启动后，可以访问 http://localhost:8000/docs 查看API文档")
    print("按 Ctrl+C 停止服务\n")
    
    try:
        # 使用uvicorn启动服务
        process = subprocess.Popen(
            [sys.executable, "-m", "uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        # 实时显示服务输出
        while True:
            output = process.stdout.readline()
            if output:
                print(output.strip())
            error = process.stderr.readline()
            if error:
                print(error.strip(), file=sys.stderr)
            
            # 检查进程是否已结束
            if process.poll() is not None:
                break
            
            # 短暂休眠，避免CPU占用过高
            time.sleep(0.1)
            
    except KeyboardInterrupt:
        print("\n正在停止服务...")
        process.terminate()
        try:
            process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            process.kill()
        print("服务已停止")
    except Exception as e:
        print(f"启动服务时发生错误: {str(e)}")

if __name__ == "__main__":
    # 检查并安装依赖
    if not check_dependencies():
        if not install_dependencies():
            sys.exit(1)
    
    # 启动服务
    start_server()